package com.posjiajia.user.api.controller;

import com.posjiajia.commom.utils.enums.ResultStatusEnum;
import com.posjiajia.commom.utils.vo.result.BaseResult;
import com.posjiajia.user.api.vo.param.LoginLogParam;
import com.posjiajia.user.core.bo.UserBo;
import com.posjiajia.user.core.po.UserLoginLogPo;
import com.posjiajia.user.core.utils.BeanTransferUtil;
import com.posjiajia.user.core.vo.UserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * @ClassName UserController
 * @Description 用户api控制器
 *
 * @author sunhaojie 3113751575@qq.com
 * @date 2016年8月23日 下午11:51:18
 */
@RequestMapping("user")
@Controller
public class UserController {

	private static final Logger logger = LoggerFactory.getLogger(UserBo.class);

	@Autowired
	private UserBo userBo;

	/**
	 * 
	 * @Title login
	 * @Description 用户登陆
	 * @return
	 *
	 * @author sunhaojie 3113751575@qq.com
	 * @date 2016年8月23日 下午11:55:34
	 */
	@RequestMapping(value = "login")
	@ResponseBody
	public BaseResult login(@RequestBody LoginLogParam param,HttpServletResponse response)
			throws IOException {
		//记录登录信息
		BaseResult result = new BaseResult(BaseResult.SUCCESS);
		logger.info("user login param:{}",param);
		UserVo userVo;
		try {
			UserLoginLogPo userLoginLogPo = BeanTransferUtil.transferType(param,UserLoginLogPo.class);
			userVo = userBo.login(param.getPin(), param.getPassword(),userLoginLogPo);
		}catch (Exception e){
			logger.error("user login fail,userPin:{}",param.getPin());
			result.setMessage("登录失败!");
			result.setStatus(500);
			return result;
		}
		result.putData("userToken", userVo.getUserToken());

		Cookie cookie = new Cookie("userToken",userVo.getUserToken());
		cookie.setPath("/");
		cookie.setMaxAge(30*60);
		response.addCookie(cookie);
		return result;
	}

	/**
	 * 用户注册
	 * @param vo
	 * @param request
     * @return
     */
	@RequestMapping(value = "post",method = RequestMethod.POST)
	@ResponseBody
	public BaseResult userRegister(UserVo vo, HttpServletRequest request, HttpServletResponse response){
		if (!checkUserParam(vo)){
			logger.info("user param is invalid");
			return returnResult(ResultStatusEnum.PARAM_ERROR.getStatus(), "USER_CHECK_PARAM_ERROR", "参数校验错误");
		}
		try {
			userBo.userRegister(vo);
		}catch (Exception e){
			logger.error("userRegister error,email:{}",vo.getEmail());
			return returnResult(ResultStatusEnum.SERVER_FAIL.getStatus(), "USER_CHECK_PARAM_ERROR", "用户注册失败");
		}

		String uuid = UUID.randomUUID().toString();
		request.getSession().setAttribute(uuid,vo);
		Cookie cookie = new Cookie("userToken",uuid);
		cookie.setPath("/");
		response.addCookie(cookie);
		return BaseResult.SUCCESS;
	}

	/**
	 * 获取user对象
	 * @param userToken
	 * @return
     */
	@RequestMapping(value = "/{userToken}",method = RequestMethod.GET)
	@ResponseBody
	public BaseResult getUser(@PathVariable String userToken) {
		
		UserVo userVo = userBo.getUserByToken(userToken);
		BaseResult success = new BaseResult(BaseResult.SUCCESS);
		success.putData("user", userVo);
		
		return success;
	}

	@RequestMapping(value = "/userId/{userId}",method = RequestMethod.GET)
	@ResponseBody
	public BaseResult getUserById(@PathVariable String userId) {
		UserVo userVo = userBo.getUserById(userId);
		BaseResult success = new BaseResult(BaseResult.SUCCESS);
		success.putData("user", userVo);

		return success;
	}

	/**
	 * 校验用户注册参数
	 * @param vo
	 */
	private boolean checkUserParam(UserVo vo) {
		if (vo == null){
			return false;
		}
		if (StringUtils.isEmpty(vo.getConfirmPassword()) || StringUtils.isEmpty(vo.getPassword()) ||
				StringUtils.isEmpty(vo.getEmail()) || StringUtils.isEmpty(vo.getMobilePhoneNo())){
			return false;
		}
		if (!vo.getConfirmPassword().equals(vo.getPassword())){
			return false;
		}
		if (vo.getOrganId() == null){
			return false;
		}
		return true;
	}

	/**
	 * 返回结果
	 * @param status
	 * @param errorCode
	 * @param message
	 * @return
	 */
	private BaseResult returnResult(int status, String errorCode, String message){
		return new BaseResult(status, errorCode, message);
	}

	/**
	 * 获取ip地址
	 * @param request
	 * @return ip
     */
	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}
